﻿using Admin.Core.Common.Attributes;
using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Xsproject;
using Admin.Core.Repository.Admin;
using Admin.Core.Repository.Xsproject.Project;
using Admin.Core.Repository.Xsproject.TaskItem;
using Admin.Core.Service.Xsproject.Project.Input;
using Admin.Core.Service.Xsproject.Project.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Xsproject.Project
{
    public class ProjectService: IProjectService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly IProjectRepository _projectRepository;
        private readonly ITaskItemRepository _taskItemRepository;
        private readonly IDictionaryRepository _dictionaryRepository;
        public ProjectService(IUser user, IMapper mapper, IProjectRepository projectRepository
            ,ITaskItemRepository taskItemRepository, IDictionaryRepository dictionaryRepository)
        {
            _user = user;
            _mapper = mapper;
            _projectRepository = projectRepository;
            _taskItemRepository = taskItemRepository;
            _dictionaryRepository = dictionaryRepository;
        }

        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _projectRepository.GetAsync<ProjectGetOutput>(id);
            return ResponseOutput.Ok(result);
        }

        public async Task<IResponseOutput> PageAsync(PageInput<ConmonFilterInput> input)
        {
            var key = input.Filter?.Name;

            var list = await _projectRepository.baseRepository.Select
            .WhereIf(key.NotNull(), a => a.Name.Contains(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a=>new ProjectListOutput {
                 Status = a.Status == 0 ? "新建" : a.Status == 1 ? "执行中" : a.Status == 2 ? "已完成" : "",
                  Model = a.Model.Name,
                  ModelCode = a.Model.Code
            });
            //var projectList = _mapper.Map<List<ProjectListOutput>>(list);
            var data = new PageOutput<ProjectListOutput>()
            {
                List = list,
                Total = total
            };
            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 获取指定字典项的
        /// </summary>
        /// <returns></returns>
        private async Task<List<DicItemOut>> GetDicModelAsync(long id )
        {
            string sql = $@"select a.id , a.name name , a.value  ,a.code  from AD_DICTIONARY a where a.enabled = 1 and a.isdeleted = 0 and a.parentid = {id}";
            var result = await _dictionaryRepository.Orm.Ado.QueryAsync<DicItemOut>(sql);
            return result;
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<IResponseOutput> AddAsync(ProjectAddInput input)
        {
            var entity = _mapper.Map<ProjectEntity>(input);
            entity.TenantId = _user.TenantId;
            var id = (await _projectRepository.baseRepository.InsertAsync(entity)).Id;
            var list = await GetDicModelAsync(input.ModelId);

            foreach (var m in list)
            {
                TaskItemEntity model = new TaskItemEntity
                {
                    FlowId = m.Value,
                    Sort = m.Code,
                    ParentId = 0,
                    ProjectId = id,
                    TenantId = _user.TenantId,
                    Status = -1,
                    TaskFlag = null,
                    TaskId = m.Id
                };
                var id1 = (await _taskItemRepository.baseRepository.InsertAsync(model)).Id;
                var ls = await GetDicModelAsync(m.Id);
                foreach (var l in ls)
                {
                    TaskItemEntity md = new TaskItemEntity
                    {
                        FlowId = l.Value,
                        Sort = l.Code,
                        ParentId = id1,
                        ProjectId = id,
                        TenantId = _user.TenantId,
                        Status = null,
                        TaskFlag = 0,
                        TaskId = l.Id
                    };
                    await _taskItemRepository.baseRepository.InsertAsync(md);
                }
            }
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 获取物料类型的下拉
        /// </summary>
        /// <returns></returns>
        //public async Task<IResponseOutput> GetXbcList()
        //{
        //    var ls = await _xbcTypeRepository.baseRepository.Select
        //          .Where(a => a.Enabled == true)
        //          .ToListAsync(a => new
        //          {
        //              Value = a.Id,
        //              Label = a.Name
        //          });
        //    return ResponseOutput.Ok(ls);
        //}


        /// <summary>
        /// 启动项目
        /// </summary>
        /// <returns></returns>
        [Transaction]
        public async Task<IResponseOutput> StartProjectAsync(long id)
        {
            var entity = await _projectRepository.baseRepository.Select.Where(x => x.Id == id && x.Status == 0).Count(out var total).ToOneAsync();
            if (total == 0)
            {
                return ResponseOutput.NotOk("项目不存在，或者状态出现异常，请联系IT处理!");
            }
            entity.Status = 1;//修改项目状态
            await _projectRepository.UpdateAsync(entity);

            var rs = await _taskItemRepository.baseRepository.Select.Where(x => x.ProjectId == entity.Id && x.ParentId == 0).Count(out var total1).ToListAsync();
            if (total1 > 0) {
                var maxentity = rs.Where(x => x.FlowId == rs.Min(z => z.FlowId)).FirstOrDefault();
                maxentity.Status = 0;//阶段状态改未待处理
                await _taskItemRepository.baseRepository.UpdateAsync(maxentity);
            }
            else
            {
                return ResponseOutput.NotOk("项目还未生产模板，请确认!");
            }
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> UpdateAsync(ProjectUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }
            var entity = await _projectRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("物料类别不存在！");
            }

            //if (input.Enabled == false)
            //{
            //    _xbcWarehouseRepository.baseRepository.Where(x => x.XbcTypeId == input.Id && x.Enabled == true).Count(out var total);
            //    if (total > 0)
            //    {
            //        return ResponseOutput.NotOk("类别已经存在启用的仓库数据，不可禁用！");
            //    }
            //}

            _mapper.Map(input, entity);
            await _projectRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            //_projectRepository.baseRepository.Where(x => x.XbcTypeId == id).Count(out var total);
            //if (total > 0)
            //{
            //    return ResponseOutput.NotOk("类别已经存在仓库数据，不可删除！");
            //}
            var result = await _projectRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }

        public async Task<IResponseOutput> BatchSoftDeleteAsync(long[] ids)
        {
            var result = await _projectRepository.SoftDeleteAsync(ids);
            return ResponseOutput.Result(result);
        }
    }
}
